#include "qemu/osdep.h"
#include "qemu/module.h"
#include "hw/i2c/i2c.h"
#include "migration/vmstate.h"
#include "hw/qdev-properties.h"
#include "hw/qdev-properties-system.h"
#include "qapi/visitor.h"
#include "trace.h"
#include "chardev/char-fe.h"
#include "hw/misc/cJSON.h"


#define TYPE_HI182X_I2CSLAVE "hi182x-i2c-slave"
#define HI182X_I2CSLAVE(obj) OBJECT_CHECK(slave_state, (obj), TYPE_HI182X_I2CSLAVE)
#define I2C_PATH "./output/data/mockdata/i2c/"
#define SMBUS_MAX_BYTE 256
#define JSON_BUF_LEN 10 * 1000

static int MSG_HEAD_LEN = 12;

enum {
    COMP_SUCCESS    = 0x0000,
    COMP_OPCODE_ERR = 0x0001,
    COMP_PARAM_ERR  = 0x0002,
    COMP_INNER_ERR  = 0x0003
};

#pragma pack(1)
struct smbus_read_req {
    uint16_t reserved;
    uint16_t opcode;
    uint32_t offset;
    uint32_t length;
    uint32_t crc32;
};
#pragma pack()

typedef struct {
    I2CSlave parent_obj;
    CharBackend chrbe;
    uint32_t count_tx;
    uint32_t count_rx;
    struct smbus_read_req req_msg;
    char *path;
    uint8_t msg[SMBUS_MAX_BYTE];       // 通过key值获取的value
    char buffer[JSON_BUF_LEN];    // json文件所有内容
    bool transfer_start;
    bool transfer_recv;
    uint8_t reg_id;
    uint32_t data_len_range;
    uint8_t rsp_len;
    bool buffer_flag;   // 缓存是否需要修改的标志
    uint8_t data[SMBUS_MAX_BYTE]; // 应用层传下来的值
    uint8_t mock_data[SMBUS_MAX_BYTE]; // 需要返回给应用层的值
    time_t last_modify;
    struct stat file_stat;
} slave_state;

static int hi182x_i2cslave_event(I2CSlave *i2c, enum i2c_event event)
{
    slave_state *s = HI182X_I2CSLAVE(i2c);
    switch (event) {
        case I2C_START_SEND:
            if (s->path == NULL) {
                s->path = g_strdup_printf("%s%d/0xe8_hi182x.json", I2C_PATH, s->reg_id);
            }            
            if (stat(s->path, &s->file_stat) != 0) {
                error_report("get hi182x mock file(%s) stat failed\n", s->path);
            } else if (s->file_stat.st_mtime != s->last_modify) {
                warn_report("Detect %s changed, Reload buffer\n", s->path);
                s->buffer_flag = false;
                s->last_modify = s->file_stat.st_mtime;
            }
            s->transfer_start = true;
            s->transfer_recv = true;
            s->count_tx = 0;
            s->count_rx = 0;
            break;
        case I2C_START_RECV:
            s->transfer_start = true;
            s->transfer_recv = false;
            break;
        case I2C_FINISH:
            s->transfer_start = false;
            s->count_tx = 0;
            break;
        case I2C_NACK:
            break;
    }
    return 0;
}

static const uint32_t crc32c_table[256] = {
    0xb1f7404bL, 0xb5365dfcL, 0xb8757b25L, 0xbcb46692L, 0xa2f33697L, 0xa6322b20L,
    0xab710df9L, 0xafb0104eL, 0x97ffadf3L, 0x933eb044L, 0x9e7d969dL, 0x9abc8b2aL,
    0x84fbdb2fL, 0x803ac698L, 0x8d79e041L, 0x89b8fdf6L, 0xfde69b3bL, 0xf927868cL,
    0xf464a055L, 0xf0a5bde2L, 0xeee2ede7L, 0xea23f050L, 0xe760d689L, 0xe3a1cb3eL,
    0xdbee7683L, 0xdf2f6b34L, 0xd26c4dedL, 0xd6ad505aL, 0xc8ea005fL, 0xcc2b1de8L,
    0xc1683b31L, 0xc5a92686L, 0x29d4f6abL, 0x2d15eb1cL, 0x2056cdc5L, 0x2497d072L,
    0x3ad08077L, 0x3e119dc0L, 0x3352bb19L, 0x3793a6aeL, 0x0fdc1b13L, 0x0b1d06a4L,
    0x065e207dL, 0x029f3dcaL, 0x1cd86dcfL, 0x18197078L, 0x155a56a1L, 0x119b4b16L,
    0x65c52ddbL, 0x6104306cL, 0x6c4716b5L, 0x68860b02L, 0x76c15b07L, 0x720046b0L,
    0x7f436069L, 0x7b827ddeL, 0x43cdc063L, 0x470cddd4L, 0x4a4ffb0dL, 0x4e8ee6baL,
    0x50c9b6bfL, 0x5408ab08L, 0x594b8dd1L, 0x5d8a9066L, 0x8571303cL, 0x81b02d8bL,
    0x8cf30b52L, 0x883216e5L, 0x967546e0L, 0x92b45b57L, 0x9ff77d8eL, 0x9b366039L,
    0xa379dd84L, 0xa7b8c033L, 0xaafbe6eaL, 0xae3afb5dL, 0xb07dab58L, 0xb4bcb6efL,
    0xb9ff9036L, 0xbd3e8d81L, 0xc960eb4cL, 0xcda1f6fbL, 0xc0e2d022L, 0xc423cd95L,
    0xda649d90L, 0xdea58027L, 0xd3e6a6feL, 0xd727bb49L, 0xef6806f4L, 0xeba91b43L,
    0xe6ea3d9aL, 0xe22b202dL, 0xfc6c7028L, 0xf8ad6d9fL, 0xf5ee4b46L, 0xf12f56f1L,
    0x1d5286dcL, 0x19939b6bL, 0x14d0bdb2L, 0x1011a005L, 0x0e56f000L, 0x0a97edb7L,
    0x07d4cb6eL, 0x0315d6d9L, 0x3b5a6b64L, 0x3f9b76d3L, 0x32d8500aL, 0x36194dbdL,
    0x285e1db8L, 0x2c9f000fL, 0x21dc26d6L, 0x251d3b61L, 0x51435dacL, 0x5582401bL,
    0x58c166c2L, 0x5c007b75L, 0x42472b70L, 0x468636c7L, 0x4bc5101eL, 0x4f040da9L,
    0x774bb014L, 0x738aada3L, 0x7ec98b7aL, 0x7a0896cdL, 0x644fc6c8L, 0x608edb7fL,
    0x6dcdfda6L, 0x690ce011L, 0xd8fba0a5L, 0xdc3abd12L, 0xd1799bcbL, 0xd5b8867cL,
    0xcbffd679L, 0xcf3ecbceL, 0xc27ded17L, 0xc6bcf0a0L, 0xfef34d1dL, 0xfa3250aaL,
    0xf7717673L, 0xf3b06bc4L, 0xedf73bc1L, 0xe9362676L, 0xe47500afL, 0xe0b41d18L,
    0x94ea7bd5L, 0x902b6662L, 0x9d6840bbL, 0x99a95d0cL, 0x87ee0d09L, 0x832f10beL,
    0x8e6c3667L, 0x8aad2bd0L, 0xb2e2966dL, 0xb6238bdaL, 0xbb60ad03L, 0xbfa1b0b4L,
    0xa1e6e0b1L, 0xa527fd06L, 0xa864dbdfL, 0xaca5c668L, 0x40d81645L, 0x44190bf2L,
    0x495a2d2bL, 0x4d9b309cL, 0x53dc6099L, 0x571d7d2eL, 0x5a5e5bf7L, 0x5e9f4640L,
    0x66d0fbfdL, 0x6211e64aL, 0x6f52c093L, 0x6b93dd24L, 0x75d48d21L, 0x71159096L,
    0x7c56b64fL, 0x7897abf8L, 0x0cc9cd35L, 0x0808d082L, 0x054bf65bL, 0x018aebecL,
    0x1fcdbbe9L, 0x1b0ca65eL, 0x164f8087L, 0x128e9d30L, 0x2ac1208dL, 0x2e003d3aL,
    0x23431be3L, 0x27820654L, 0x39c55651L, 0x3d044be6L, 0x30476d3fL, 0x34867088L,
    0xec7dd0d2L, 0xe8bccd65L, 0xe5ffebbcL, 0xe13ef60bL, 0xff79a60eL, 0xfbb8bbb9L,
    0xf6fb9d60L, 0xf23a80d7L, 0xca753d6aL, 0xceb420ddL, 0xc3f70604L, 0xc7361bb3L,
    0xd9714bb6L, 0xddb05601L, 0xd0f370d8L, 0xd4326d6fL, 0xa06c0ba2L, 0xa4ad1615L,
    0xa9ee30ccL, 0xad2f2d7bL, 0xb3687d7eL, 0xb7a960c9L, 0xbaea4610L, 0xbe2b5ba7L,
    0x8664e61aL, 0x82a5fbadL, 0x8fe6dd74L, 0x8b27c0c3L, 0x956090c6L, 0x91a18d71L,
    0x9ce2aba8L, 0x9823b61fL, 0x745e6632L, 0x709f7b85L, 0x7ddc5d5cL, 0x791d40ebL,
    0x675a10eeL, 0x639b0d59L, 0x6ed82b80L, 0x6a193637L, 0x52568b8aL, 0x5697963dL,
    0x5bd4b0e4L, 0x5f15ad53L, 0x4152fd56L, 0x4593e0e1L, 0x48d0c638L, 0x4c11db8fL,
    0x384fbd42L, 0x3c8ea0f5L, 0x31cd862cL, 0x350c9b9bL, 0x2b4bcb9eL, 0x2f8ad629L,
    0x22c9f0f0L, 0x2608ed47L, 0x1e4750faL, 0x1a864d4dL, 0x17c56b94L, 0x13047623L,
    0x0d432626L, 0x09823b91L, 0x04c11d48L, 0x000000ffL
};

static uint32_t calc_crc32(uint8_t *data, uint8_t length)
{
    uint32_t crc = 0xFFFFFFFF;
    for (int i = 0; i < length; i++) {
        uint8_t index = ((crc >> 24) ^ data[i]) & 0xFF;
        crc = crc32c_table[index] ^ (crc << 8);
    }
    return crc;
}

static uint16_t write_buffer(slave_state *s)
{
    FILE *f = fopen(s->path, "r+");
    if (f == NULL) {
        error_report("line : %d, i2c%d open hi182x file failed\n", __LINE__, s->reg_id);
        return COMP_PARAM_ERR;
    }
    int ret = fseek(f, 0, SEEK_END);
    if (ret != 0) {
        goto err;
    }
    int file_size = ftell(f);
    if (file_size > JSON_BUF_LEN) {
        goto err;
    }
    ret = fseek(f, 0, SEEK_SET);
    if (ret != 0) {
        goto err;
    }
    
    ret = fread(s->buffer, sizeof(char), file_size, f);
    if (ret == 0) {
        goto err;
    }
    fclose(f);
    s->buffer_flag = true;
    return COMP_SUCCESS;

err:
    warn_report("i2c%d write hi182x buffer failed\n", s->reg_id);
    fclose(f);
    return COMP_PARAM_ERR;
}

static uint8_t cjson_read_buffer_data(slave_state *s)
{
    cJSON *root = cJSON_Parse(s->buffer);
    if (root == NULL) {
        error_report("parse error\n");
        return COMP_INNER_ERR;
    }
    char *key = g_strdup_printf("0x%04x", s->req_msg.opcode);
    cJSON *value = cJSON_GetObjectItem(root, key);
    g_free(key);
    if (value == NULL || !cJSON_IsArray(value)) {
        cJSON_Delete(root);
        return COMP_OPCODE_ERR;
    }
    int buffer_len = cJSON_GetArraySize(value);
    cJSON *item;
    // mock_data数组前2位分别为读写标志,长度校验
    item = cJSON_GetArrayItem(value, 0);
    s->data_len_range = cJSON_GetNumberValue(item);    
    for (int i = 0; i < buffer_len - 1; i++) {
        // mock数据从第2字节开始
        item = cJSON_GetArrayItem(value, i + 1);
        if (item && cJSON_IsString(item)) {
            s->msg[i] = (uint8_t)strtol(item->valuestring, NULL, 16);
        } else {
            warn_report("Invalid array item at index: %d\n", i);
            s->msg[i] = 0x00;
        }
    }
    cJSON_Delete(root);
    return COMP_SUCCESS;
}

static uint8_t hi182x_i2cslave_rx(I2CSlave *i2c)
{
    slave_state *s = HI182X_I2CSLAVE(i2c);
    int rx = s->mock_data[s->count_rx];
    
    // 不足请求长度的数据填充0xff
    if (s->count_rx >= s->rsp_len) {
        s->count_rx++;
        return 0xff;
    }

    s->count_rx++;
    return rx;
}

static uint8_t check_data_byte(slave_state *s)
{
    uint8_t crc_calc_len = MSG_HEAD_LEN;
    uint32_t crc_result;
    // 校验入参长度
    if (s->req_msg.offset >= s->data_len_range - MSG_HEAD_LEN) {
        return COMP_PARAM_ERR;
    }
    crc_result = calc_crc32(s->data, crc_calc_len);
    if (crc_result != s->req_msg.crc32) {
        return COMP_OPCODE_ERR;
    }
    return COMP_SUCCESS;
}

static void get_mock_data(slave_state *s, uint16_t comp_code)
{
    uint8_t count_num = 0;
    if (comp_code != COMP_SUCCESS) {
        memset(s->msg, 0, sizeof(s->msg));
        s->msg[0] = comp_code & 0xFF;
        s->msg[1] = (comp_code >> 8) & 0xFF;
    }
    for (int i = 0; i < s->data_len_range && count_num < s->req_msg.length + MSG_HEAD_LEN; i++, count_num++) {
        if (i == MSG_HEAD_LEN) {
            i += s->req_msg.offset;
        }
        s->mock_data[count_num] = s->msg[i];
    }
    uint32_t crc_result = calc_crc32(s->mock_data, count_num);
    for (int i = 0; i < 4; i++) {
        s->mock_data[count_num] = (crc_result >> i * 8) & 0xFF;
        count_num++;
    }
    s->rsp_len = count_num;
}

static int hi182x_i2cslave_tx(I2CSlave *i2c, uint8_t data)
{
    slave_state *s = HI182X_I2CSLAVE(i2c);
    s->data[s->count_tx] = data;

    // 私有SMBUS协议请求长度16
    if (s->count_tx == 15) {
        s->req_msg = *(struct smbus_read_req *)s->data;
        memset(s->msg, 0, sizeof(s->msg));
        uint16_t ret;
        ret = write_buffer(s);
        if (ret != COMP_SUCCESS) {
            get_mock_data(s, ret);
            return 0;
        }
        ret = cjson_read_buffer_data(s);
        if (ret != COMP_SUCCESS) {
            get_mock_data(s, ret);
            return 0;
        }
        ret = check_data_byte(s);
        if (ret != COMP_SUCCESS) {
            get_mock_data(s, ret);
            return 0;
        }
        get_mock_data(s, ret);
        return 0;
    }
    s->count_tx++;
    return 0;
}

static void hi182x_i2cslave_reset(DeviceState *dev)
{
    slave_state *s = HI182X_I2CSLAVE(dev);
    s->transfer_start = false;
}


static void hi182x_i2cslave_realize(DeviceState *dev, Error **errp)
{
    slave_state *s = HI182X_I2CSLAVE(dev);
    s->transfer_recv = false;
}

static void generic_i2cslave_access_addr(Object *obj, Visitor *v, const char *name, void *opaque, Error **errp)
{
    uint8_t *ptr = (uint8_t *)object_field_prop_ptr(obj, (Property *)opaque);
    visit_type_uint8(v, name, ptr, errp);
}

static const PropertyInfo generic_i2cslave_prop_regaddr = {
    .name  = "uint8",
    .get   = generic_i2cslave_access_addr,
    .set   = generic_i2cslave_access_addr,
};

static Property hi182x_i2cslave_properties[] = {
    DEFINE_PROP_UNSIGNED_NODEFAULT("reg-id", slave_state, reg_id, generic_i2cslave_prop_regaddr, uint8_t),
    DEFINE_PROP_END_OF_LIST(),
};


static void hi182x_i2cslave_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);
    k->event = hi182x_i2cslave_event;
    k->recv = hi182x_i2cslave_rx;
    k->send = hi182x_i2cslave_tx;
    dc->reset = hi182x_i2cslave_reset;
    dc->realize = hi182x_i2cslave_realize;
    device_class_set_props(dc, hi182x_i2cslave_properties);
}

static void hi182x_i2cslave_init(Object *obj)
{
    slave_state *s = HI182X_I2CSLAVE(obj);
    s->transfer_start = false;
}

static const TypeInfo hi182x_i2cslave_info = {
    .name          = TYPE_HI182X_I2CSLAVE,
    .parent        = TYPE_I2C_SLAVE,
    .instance_size = sizeof(slave_state),
    .class_init    = hi182x_i2cslave_class_init,
    .instance_init = hi182x_i2cslave_init,
};

static void hi182x_i2cslave_register_types(void)
{
    type_register_static(&hi182x_i2cslave_info);
}

type_init(hi182x_i2cslave_register_types)